package com.lwj.springbootvue.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lwj.springbootvue.model.User;
import com.lwj.springbootvue.model.vo.LoginUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;


@Component
public class JwtUtils {

    // 秘钥
    private static final String SECRET="King-all-secret";


    // 创建jwt token
    public static  String createToken(LoginUser loginUser){
        // 设置登录时间
        loginUser.setLoginTime(System.currentTimeMillis());
        Algorithm algorithm=Algorithm.HMAC256(SECRET);// 设置加密方式
        // 设置token过期时间
        Date expireDate =
                new Date(System.currentTimeMillis() + 3600 * 20000); // 设置过期时间
        // 序列化封装  user登录用户
        String jsonString = JSON.toJSONString(loginUser.getUser());
        // 生成jwt
        return JWT.create()
                .withSubject(jsonString)
                .withClaim("loginTime",loginUser.getLoginTime() )
                .withExpiresAt(expireDate)
                .sign(algorithm);
    }




    // 获取token的荷载
    public static User getTokenUser(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            User user = JSON.parseObject(jwt.getSubject(),User.class);// 反序列化 user对象
            return user;
        } catch (JWTVerificationException exception) {
            // 处理验证异常，例如token无效或过期
            return null;
        }
    }


    // 获取token的荷载
    public static Long getLoginTimeFromToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("loginTime").asLong();
        } catch (JWTVerificationException exception) {
            // 处理验证异常，例如token无效或过期
            return null;
        }
    }


    // 判断token 是否过期
    public static boolean isTokenExpired(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getExpiresAt().before(new Date());
        } catch (JWTVerificationException exception) {
            return true;
        }
    }


}


